package serialize

import (
	"github.com/hyperway/pkg/component"
	"github.com/hyperway/pkg/constant"
	"github.com/json-iterator/go"
)

func init() {
	component.RegisterSerializer(constant.JsonSerializerName, NewJsonSerializer())
}

func NewJsonSerializer() component.Serializer {
	return &JSONSerializer{json: jsoniter.ConfigCompatibleWithStandardLibrary}
}

type JSONSerializer struct {
	json jsoniter.API
}

// ToBytes 将对象序列化为字节数组
func (s *JSONSerializer) ToBytes(v interface{}) ([]byte, error) {
	return s.json.Marshal(v)
}

// ToObject 将字节数组反序列化为对象
func (s *JSONSerializer) ToObject(d []byte, v interface{}) error {
	return s.json.Unmarshal(d, v)
}

// JSONToBytes 将对象序列化为字节数组
func JSONToBytes(v interface{}) ([]byte, error) {
	return component.NamedSerializers[constant.JsonSerializerName].ToBytes(v)
}

// JSONToObject 将字节数组反序列化为对象；
func JSONToObject(data []byte, out interface{}) error {
	return component.NamedSerializers[constant.JsonSerializerName].ToObject(data, out)
}
